BB_URL = 'https://demo.remotegrity.org/BBinOrder.php';

function showBallot(ballot){
	var $ballot = $(ballot);
	var $questions = $ballot.find('question');

	var w = '';
	$questions.each(function(i){
		w += showQuestion(this);
	});

	if($ballot.attr('locked') == 'true'){
		return '<div class="ballot locked"><div class="webserial">locked: ' + $ballot.attr('webSerial') + '</div>' + w + '</div>';
	}
	else{
		return '<div class="ballot"><div class="webserial">' + $ballot.attr('webSerial') + '</div>' + w + 
			'<div class="overwritten">overwrittenBy: ' + ($ballot.attr('overwrittenBy') ? $ballot.attr('overwrittenBy') : '-') + '</div></div>';
	}
}

function showQuestion(question) {
	var $q = $(question);
	var $symbols = $q.find('symbol');
	
	var w = '';
	$symbols.each(function(i){
		w += showSymbol(this);
	});

	return '<div class="question">' + $q.attr("id") + ") question " + w +	"</div>";
}

function showSymbol(symbol) {
	var $s = $(symbol);
	
	return '<div class="symbol">' + $s.attr('id') + "] " + $s.attr("code") + '</div>';
}


function verify(data){
	//WebLogin to track (that user entered)
	var weblogin = $('#weblogin').val();
	if(weblogin == ''){ 
		weblogin = false; 
	}

	//all values from Bulletin Board
	var $ballots = $(data).find('entry');

	//this will be different for all elections
	var currentHash = 'FirstEntry';

	//output, where we are 'writing'
	var $output = $('#output');
	var $ballot_found = false; //$('<div id="balllot_weblogin"></div>');
	//var $outputBB = $('#outputBB');
      
	//foreach ballot, test hashes
	$ballots.each(function(i){
		var $elem = $(this);
		if($elem.attr('type') == 'lockIn'){
			currentHash = Crypto.SHA256(currentHash + ':' + $elem.attr('lockIn'));
		} else {
			currentHash = Crypto.SHA256(currentHash + ':' + $elem.attr('webLogin') + ':' + $elem.attr('webSerial') + ':' + $elem.attr('Vote'));
		}

		if($elem.attr("hash") != currentHash){
			$output.append('<div style="margin-bottom:5px"><span class="err">Hashes do not match!</span> Ballot id: ' + $elem.attr('id') + 
				'<br />Should be: <span class="hash">' + currentHash + '</span>; Is: <span class="hash">' + $elem.attr('hash') + '</span></div>');
		}

		currentHash = $elem.attr('hash');

		if(weblogin == $elem.attr('webSerial')){
			$ballot_found = $elem.clone();
		}
	});
  
	//$output.append('<div id="ballot_weblogin">' + showBallot($ballot_found) + '</div>');
	if($ballot_found){
		$output.append('<div class="bigskip" style="font-weight:bold;margin-bottom:5px;">Ballot with entered weblogin:</div>' + showBallot($ballot_found));
	}
	else{
		$output.append('<div class="err">Bulletin Board does not contain ballot with entered weblogin!</div>');
	}
	
	hideLoader();
	$('#step3').show();
}

//load specific css code
$('head').append('<link rel=stylesheet HREF="css/remotegrity.css" type="text/css">');

$('#btn_step2').click(function(){ showLoader('#step2'); $.get(BB_URL, verify); });
hideLoader();